﻿using System;
using UnityEngine;

namespace Assist {
    public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {

        private static readonly object Lock = new object();
        private static T _mInstance;
        public static T Instance {
            get {
                lock (Lock) {
                    if (_mInstance != null) return _mInstance;
                    _mInstance = FindObjectOfType<T>();
                    if (_mInstance != null) return _mInstance;
                    var go = new GameObject(typeof(T).Name);
                    _mInstance = go.AddComponent<T>();
                    if (Application.isPlaying) DontDestroyOnLoad(go);
                    return _mInstance;
                }
            }
        }

    }
    public class SingletonCanDestroy<T> : MonoBehaviour where T : MonoBehaviour {

        private static readonly object Lock = new object();
        private static T _mInstance;
        public static T Instance {
            get {
                lock (Lock) {
                    if (_mInstance != null) return _mInstance;
                    _mInstance = FindObjectOfType<T>();
                    if (_mInstance != null) return _mInstance;
                    var go = new GameObject(typeof(T).Name);
                    _mInstance = go.AddComponent<T>();
                    return _mInstance;
                }
            }
        }

    }
    public class SingletonScript<T> where T : new() {

        private static readonly Lazy<T> Lazy = new Lazy<T>(() => new T());
        public static T Instance => Lazy.Value;

    }

    // public class SingletonProvider<T> : LcBaseProvider where T : new()
    // {
    //     private static readonly Lazy<T> Lazy = new Lazy<T>(() => new T());
    //     public static T Instance => Lazy.Value;
    // }
}